package im.oen.boot.common.utils;

import com.thoughtworks.xstream.XStream;

import java.util.Map;
import java.util.concurrent.DelayQueue;

/**
 * XML工具
 *
 * @author Kevin.Xu
 */
public class XmlUtil {

    private static XStream XS = new XStream();

    public static <T> T toObj(String xml, String root, Class<T> clazz) {
        DelayQueue qu = new DelayQueue();

        XS.ignoreUnknownElements();
        XS.alias(root, clazz);
        return (T) XS.fromXML(xml);
    }

    public static <T> T toObj(String xml, Class<T> clazz) {
        String root = clazz.getSimpleName();
        return XmlUtil.toObj(xml, root, clazz);
    }

    public static String toXml(String root, Object obj) {
        XS.ignoreUnknownElements();
        XS.alias(root, obj.getClass());
        return XS.toXML(obj);
    }

    public static String toXml(Object obj) {
        String root = obj.getClass().getName();
        return XmlUtil.toXml(root, obj);
    }

    public static String toXml(Map<String, Object> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append("<").append(entry.getKey()).append("><![CDATA[").append(entry.getValue()).append("]]></").append(entry.getKey()).append(">");
        }
        return sb.toString();
    }
}
